// 颜色工具包
class ColorToolkit {
    // 常用颜色预设
    static colorPresets = {
        '常用色': [
            '#FF0000', '#FF8000', '#FFFF00', '#80FF00', '#00FF00', '#00FF80',
            '#00FFFF', '#0080FF', '#0000FF', '#8000FF', '#FF00FF', '#FF0080',
            '#000000', '#404040', '#808080', '#C0C0C0', '#FFFFFF'
        ],
        '材料设计': [
            '#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3',
            '#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39',
            '#FFEB3B', '#FFC107', '#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B'
        ],
        'Tailwind CSS': [
            '#EF4444', '#F59E0B', '#10B981', '#3B82F6', '#8B5CF6', '#EC4899',
            '#06B6D4', '#84CC16', '#F97316', '#6366F1', '#14B8A6', '#F59E0B'
        ],
        '渐变起始色': [
            '#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe', '#43e97b',
            '#fa709a', '#ffecd2', '#a8edea', '#d299c2', '#89f7fe', '#66a6ff'
        ]
    };

    // HEX转RGB
    static hexToRgb(hex) {
        try {
            // 移除#符号
            hex = hex.replace('#', '');
            
            // 支持3位和6位HEX
            if (hex.length === 3) {
                hex = hex.split('').map(char => char + char).join('');
            }
            
            if (hex.length !== 6) {
                return { success: false, error: '无效的HEX颜色格式' };
            }
            
            const r = parseInt(hex.substr(0, 2), 16);
            const g = parseInt(hex.substr(2, 2), 16);
            const b = parseInt(hex.substr(4, 2), 16);
            
            if (isNaN(r) || isNaN(g) || isNaN(b)) {
                return { success: false, error: '无效的HEX颜色值' };
            }
            
            return { success: true, data: { r, g, b } };
        } catch (error) {
            return { success: false, error: 'HEX转换失败' };
        }
    }

    // RGB转HEX
    static rgbToHex(r, g, b) {
        try {
            // 验证RGB值范围
            if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
                return { success: false, error: 'RGB值必须在0-255之间' };
            }
            
            const hex = '#' + [r, g, b].map(x => {
                const hex = Math.round(x).toString(16);
                return hex.length === 1 ? '0' + hex : hex;
            }).join('').toUpperCase();
            
            return { success: true, data: hex };
        } catch (error) {
            return { success: false, error: 'RGB转换失败' };
        }
    }

    // RGB转HSL
    static rgbToHsl(r, g, b) {
        try {
            r /= 255;
            g /= 255;
            b /= 255;
            
            const max = Math.max(r, g, b);
            const min = Math.min(r, g, b);
            let h, s, l = (max + min) / 2;
            
            if (max === min) {
                h = s = 0;
            } else {
                const d = max - min;
                s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
                
                switch (max) {
                    case r: h = (g - b) / d + (g < b ? 6 : 0); break;
                    case g: h = (b - r) / d + 2; break;
                    case b: h = (r - g) / d + 4; break;
                }
                h /= 6;
            }
            
            return {
                success: true,
                data: {
                    h: Math.round(h * 360),
                    s: Math.round(s * 100),
                    l: Math.round(l * 100)
                }
            };
        } catch (error) {
            return { success: false, error: 'RGB转HSL失败' };
        }
    }

    // HSL转RGB
    static hslToRgb(h, s, l) {
        try {
            h = ((h % 360) + 360) % 360; // 确保h在0-360范围内
            s = Math.max(0, Math.min(100, s)) / 100; // 确保s在0-1范围内
            l = Math.max(0, Math.min(100, l)) / 100; // 确保l在0-1范围内
            
            const c = (1 - Math.abs(2 * l - 1)) * s;
            const x = c * (1 - Math.abs((h / 60) % 2 - 1));
            const m = l - c / 2;
            let r, g, b;
            
            if (0 <= h && h < 60) {
                r = c; g = x; b = 0;
            } else if (60 <= h && h < 120) {
                r = x; g = c; b = 0;
            } else if (120 <= h && h < 180) {
                r = 0; g = c; b = x;
            } else if (180 <= h && h < 240) {
                r = 0; g = x; b = c;
            } else if (240 <= h && h < 300) {
                r = x; g = 0; b = c;
            } else if (300 <= h && h < 360) {
                r = c; g = 0; b = x;
            }
            
            return {
                success: true,
                data: {
                    r: Math.round((r + m) * 255),
                    g: Math.round((g + m) * 255),
                    b: Math.round((b + m) * 255)
                }
            };
        } catch (error) {
            return { success: false, error: 'HSL转RGB失败' };
        }
    }

    // 解析任意颜色格式
    static parseColor(colorString) {
        try {
            if (!colorString || typeof colorString !== 'string') {
                return { success: false, error: '颜色值不能为空' };
            }
            
            colorString = colorString.trim();
            
            // HEX格式
            if (colorString.startsWith('#')) {
                const hexResult = this.hexToRgb(colorString);
                if (hexResult.success) {
                    const hslResult = this.rgbToHsl(hexResult.data.r, hexResult.data.g, hexResult.data.b);
                    return {
                        success: true,
                        data: {
                            format: 'hex',
                            hex: colorString.toUpperCase(),
                            rgb: hexResult.data,
                            hsl: hslResult.success ? hslResult.data : null
                        }
                    };
                }
                return hexResult;
            }
            
            // RGB格式
            const rgbMatch = colorString.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
            if (rgbMatch) {
                const r = parseInt(rgbMatch[1]);
                const g = parseInt(rgbMatch[2]);
                const b = parseInt(rgbMatch[3]);
                
                const hexResult = this.rgbToHex(r, g, b);
                const hslResult = this.rgbToHsl(r, g, b);
                
                return {
                    success: true,
                    data: {
                        format: 'rgb',
                        hex: hexResult.success ? hexResult.data : null,
                        rgb: { r, g, b },
                        hsl: hslResult.success ? hslResult.data : null
                    }
                };
            }
            
            // HSL格式
            const hslMatch = colorString.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
            if (hslMatch) {
                const h = parseInt(hslMatch[1]);
                const s = parseInt(hslMatch[2]);
                const l = parseInt(hslMatch[3]);
                
                const rgbResult = this.hslToRgb(h, s, l);
                const hexResult = rgbResult.success ? this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b) : null;
                
                return {
                    success: true,
                    data: {
                        format: 'hsl',
                        hex: hexResult ? hexResult.data : null,
                        rgb: rgbResult.success ? rgbResult.data : null,
                        hsl: { h, s, l }
                    }
                };
            }
            
            return { success: false, error: '不支持的颜色格式' };
        } catch (error) {
            return { success: false, error: '颜色解析失败' };
        }
    }

    // 生成颜色调色板
    static generatePalette(baseColor, type = 'monochrome') {
        try {
            const parseResult = this.parseColor(baseColor);
            if (!parseResult.success) {
                return parseResult;
            }
            
            const { rgb, hsl } = parseResult.data;
            const palette = [];
            
            switch (type) {
                case 'monochrome':
                    // 单色调色板 - 改变亮度
                    for (let i = 10; i <= 90; i += 10) {
                        const rgbResult = this.hslToRgb(hsl.h, hsl.s, i);
                        if (rgbResult.success) {
                            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
                            if (hexResult.success) {
                                palette.push({
                                    hex: hexResult.data,
                                    rgb: rgbResult.data,
                                    hsl: { h: hsl.h, s: hsl.s, l: i },
                                    name: `亮度 ${i}%`
                                });
                            }
                        }
                    }
                    break;
                    
                case 'analogous':
                    // 类似色 - 色相偏移±30度
                    for (let offset of [-30, -15, 0, 15, 30]) {
                        const newH = (hsl.h + offset + 360) % 360;
                        const rgbResult = this.hslToRgb(newH, hsl.s, hsl.l);
                        if (rgbResult.success) {
                            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
                            if (hexResult.success) {
                                palette.push({
                                    hex: hexResult.data,
                                    rgb: rgbResult.data,
                                    hsl: { h: newH, s: hsl.s, l: hsl.l },
                                    name: offset === 0 ? '基色' : `${offset > 0 ? '+' : ''}${offset}°`
                                });
                            }
                        }
                    }
                    break;
                    
                case 'complementary':
                    // 补色方案
                    const complementaryH = (hsl.h + 180) % 360;
                    const colors = [
                        { h: hsl.h, name: '基色' },
                        { h: complementaryH, name: '补色' }
                    ];
                    
                    colors.forEach(color => {
                        const rgbResult = this.hslToRgb(color.h, hsl.s, hsl.l);
                        if (rgbResult.success) {
                            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
                            if (hexResult.success) {
                                palette.push({
                                    hex: hexResult.data,
                                    rgb: rgbResult.data,
                                    hsl: { h: color.h, s: hsl.s, l: hsl.l },
                                    name: color.name
                                });
                            }
                        }
                    });
                    break;
                    
                case 'triadic':
                    // 三角色方案
                    const triadicColors = [
                        { h: hsl.h, name: '基色' },
                        { h: (hsl.h + 120) % 360, name: '三角色1' },
                        { h: (hsl.h + 240) % 360, name: '三角色2' }
                    ];
                    
                    triadicColors.forEach(color => {
                        const rgbResult = this.hslToRgb(color.h, hsl.s, hsl.l);
                        if (rgbResult.success) {
                            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
                            if (hexResult.success) {
                                palette.push({
                                    hex: hexResult.data,
                                    rgb: rgbResult.data,
                                    hsl: { h: color.h, s: hsl.s, l: hsl.l },
                                    name: color.name
                                });
                            }
                        }
                    });
                    break;
                    
                case 'tetradic':
                    // 四角色方案
                    const tetradicColors = [
                        { h: hsl.h, name: '基色' },
                        { h: (hsl.h + 90) % 360, name: '90°' },
                        { h: (hsl.h + 180) % 360, name: '180°' },
                        { h: (hsl.h + 270) % 360, name: '270°' }
                    ];
                    
                    tetradicColors.forEach(color => {
                        const rgbResult = this.hslToRgb(color.h, hsl.s, hsl.l);
                        if (rgbResult.success) {
                            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
                            if (hexResult.success) {
                                palette.push({
                                    hex: hexResult.data,
                                    rgb: rgbResult.data,
                                    hsl: { h: color.h, s: hsl.s, l: hsl.l },
                                    name: color.name
                                });
                            }
                        }
                    });
                    break;
                    
                default:
                    return { success: false, error: '不支持的调色板类型' };
            }
            
            return { success: true, data: { type, palette } };
        } catch (error) {
            return { success: false, error: '生成调色板失败' };
        }
    }

    // 获取颜色亮度
    static getColorBrightness(hex) {
        try {
            const rgbResult = this.hexToRgb(hex);
            if (!rgbResult.success) {
                return rgbResult;
            }
            
            const { r, g, b } = rgbResult.data;
            // 使用相对亮度公式
            const brightness = (0.299 * r + 0.587 * g + 0.114 * b);
            
            return { 
                success: true, 
                data: { 
                    brightness: Math.round(brightness),
                    percentage: Math.round((brightness / 255) * 100),
                    isDark: brightness < 128
                } 
            };
        } catch (error) {
            return { success: false, error: '计算亮度失败' };
        }
    }

    // 获取颜色对比度
    static getColorContrast(color1, color2) {
        try {
            const brightness1 = this.getColorBrightness(color1);
            const brightness2 = this.getColorBrightness(color2);
            
            if (!brightness1.success || !brightness2.success) {
                return { success: false, error: '无法计算颜色亮度' };
            }
            
            const l1 = brightness1.data.brightness;
            const l2 = brightness2.data.brightness;
            
            const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
            
            let level = 'AA++';
            if (ratio >= 7) level = 'AAA';
            else if (ratio >= 4.5) level = 'AA';
            else if (ratio >= 3) level = 'AA大字体';
            else level = '不达标';
            
            return {
                success: true,
                data: {
                    ratio: Math.round(ratio * 100) / 100,
                    level,
                    isAccessible: ratio >= 4.5
                }
            };
        } catch (error) {
            return { success: false, error: '计算对比度失败' };
        }
    }

    // 获取颜色预设
    static getColorPresets() {
        return { success: true, data: this.colorPresets };
    }

    // 随机颜色生成
    static generateRandomColor(options = {}) {
        try {
            const { 
                hueMin = 0, 
                hueMax = 360, 
                saturationMin = 20, 
                saturationMax = 100,
                lightnessMin = 20,
                lightnessMax = 80
            } = options;
            
            const h = Math.floor(Math.random() * (hueMax - hueMin) + hueMin);
            const s = Math.floor(Math.random() * (saturationMax - saturationMin) + saturationMin);
            const l = Math.floor(Math.random() * (lightnessMax - lightnessMin) + lightnessMin);
            
            const rgbResult = this.hslToRgb(h, s, l);
            if (!rgbResult.success) {
                return rgbResult;
            }
            
            const hexResult = this.rgbToHex(rgbResult.data.r, rgbResult.data.g, rgbResult.data.b);
            if (!hexResult.success) {
                return hexResult;
            }
            
            return {
                success: true,
                data: {
                    hex: hexResult.data,
                    rgb: rgbResult.data,
                    hsl: { h, s, l }
                }
            };
        } catch (error) {
            return { success: false, error: '生成随机颜色失败' };
        }
    }
}